﻿import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect,Link} from 'mirrorx';
import { List, InputItem, WhiteSpace, WingBlank, Button,Checkbox,Picker,Flex,Modal } from 'antd-mobile';
import { FormattedMessage} from 'react-intl';
import {API} from '../api';

const ListItem = List.Item;
const CheckboxItem = Checkbox.CheckboxItem;


if (!actions.surrenderInfo) {   
    mirror.model({
        name: 'surrenderInfo',
        initialState: {
           policyInfo:{}
        },
        reducers: {
            setpolicyInfo(state,data){
                return Object.assign({}, state, {policyInfo:data});
            }
        },
        effects: {     
		   queryPolicyInfo(opts){	
			 	let  orderNo = T.urlQuery("orderNo")
				const oderModel = T.fetch2({				
					url:API.oderDetail.path,
					data:{
						onlyLocal: 'yes',
						orderNo: orderNo
					},
				})
				oderModel.then((res)=>{
					const policyInfo = res.data
					actions.surrenderInfo.setpolicyInfo(policyInfo)
					console.log(policyInfo)
					opts.callback && opts.callback()
				});		
			}
        }
    })
}

class App extends React.Component { 
	constructor(props) {
		super(props);

		this.state={
			reason:[],
			chooseAll:false,
			insureCheckMap:[],
			surrenderResult:null,
			isPass:false
		}

		const Lang = window.LangMessage ||{};
		this.stateMap = {
			"EFFECTIVE":Lang.valid || "有效",
			"EXPIRY":Lang.not_valid ||"失效",
			"TERMINATION":Lang.end ||"终止"
		}

		this.policyNo = T.urlQuery("policyNo")
		this.orderNo = T.urlQuery("orderNo")
	} 

	componentDidMount(){
		// const {policyInfo} = this.props;		
		//  if(!policyInfo || (policyInfo && !policyInfo.length)){
        //    actions.surrenderInfo.requestPolicyInfo((policyInfo)=>{
		// 	  this.initCheckMap(policyInfo)
		// 	});
		// }	
		actions.surrenderInfo.queryPolicyInfo({
			callback:()=>{
				//默认选中计划
				this.setState({
					insureCheckMap:[this.policyNo]
				});
			}
		})		
	}	

	// initCheckMap(policyInfo){
	// 	let insureCheckMap = this.state.insureCheckMap
	// 	if(policyInfo && policyInfo.policyProductList){
	// 		policyInfo.policyProductList.forEach((item)=>{
	// 			if(item.status =="EFFECTIVE"){
	// 				insureCheckMap[item.productId] = true;
	// 			}
	// 		})
	// 	}
	// 	this.setState({
	// 		insureCheckMap
	// 	});
	// }
	
	chooseInsure = (event)=>{
		if (event.target.checked){
			this.setState({
				insureCheckMap:[this.policyNo]
			});
		}	
		else {
			this.setState({
				insureCheckMap:[]
			});
		}
	}

	getParam=()=>{
		const Lang = window.LangMessage ||{};
		
		if(!this.state.insureCheckMap.length){
			T.showError(Lang.choose_policy_surrender ||"请选择您希望退保的险种",1);
			return false;
		}

		if(!this.state.reason.length){
			T.showError(Lang.choose_surrender_reason ||"请选择退保原因",1.5)
			return false;
		}
		
		return  {
			"orderNo" : this.orderNo,
			"reasonCause" : this.state.reason.join(""),
		}
	}

	submitTry = ()=>{
		let data = this.getParam();	
		if (data){
			if (!this.state.isPass){
				const requestModel = T.fetch2({				
					url:API.preCalculate.path,
					data:data,
					loading:true
				})
				requestModel.then((res)=>{
					console.log(res)
					if(res.success){
						this.setState({
							surrenderResult:res.data,
							isPass:true
						})
					}
				});		
			}
			else {
				//跳转到支付方式选择页
				actions.routing.push({
					pathname:'surrender-payway',
					search:'?insures='+this.props.policyInfo.planName //计划名称
					+'&reason='+data.reasonCause  //退保原因
					+'&feeAmount='+this.state.surrenderResult.feeAmount  //退保金额
					+'&orderNo='+data.orderNo   //订单编号
					+'&surrenderNo='+this.state.surrenderResult.surrenderNo //退保单号
				})
			}
		}	
	}

	render() {
		const Lang = window.LangMessage ||{};
		const data = this.props.policyInfo || {};
		

		const list=[
			{label:Lang.financial_difficult || "财务困难",value:Lang.financial_difficult || "财务困难"},
			{label:Lang.product_not_meet_demand || "产品不满足需求",value:Lang.product_not_meet_demand || "产品不满足需求"},
			{label:Lang.coverage_high_low || "保额过高/过低",value:Lang.coverage_high_low || "保额过高/过低"},
			{label:Lang.other || "其他",value:Lang.other || "其他"}];
		

		let btnText = this.state.isPass ? Lang.next ||"下一步" : (Lang.trial || 'お見積もり' || "试算");
		
		return (<div className="surrnder-wrap">
			<div className="product-head bor-bottom">
				<p className="tal strong f30">{data.channelGoodsName}</p>
				<p className="tar 28" style={{textAlign:'left'}}>
				 <FormattedMessage id='policy_no' defaultMessage='保单号'/>：{this.policyNo}
				</p>
			</div>
			<div>
				<p className="line-item ml10"><FormattedMessage id='choose_policy_surrender' defaultMessage='请选择您希望退保的险种'/>：</p>
			</div>
			<List>
				 <ListItem arrow="horizontal">
					<Checkbox className="mr20" defaultChecked  onChange={this.chooseInsure} />
					{data.planName}
				</ListItem>
			</List>

			<WhiteSpace/>
			<List>
				<Picker data={list} cols={1} value={this.state.reason} onChange={(value)=>this.setState({reason:value})} extra={Inter.please_select}>
					<ListItem arrow="horizontal"><FormattedMessage id='surrender_reason' defaultMessage='退保原因'/></ListItem>
				</Picker>
			</List>
			
			{this.state.surrenderResult && 
				<div className="result-box border f28">
					{this.state.surrenderResult.feeDetailList && this.state.surrenderResult.feeDetailList.map((item,index)=>{
						let flag = item.money && /^\s*\-/.test(item.money) ?"-":"+";
						return <div className="clearfix result-item" key={index}>
									<div className="fl">（{flag}）{item.name}</div>
									<div className="fr">{T.formatPrice(T.cutPrice(item.money))} SGD</div>
								</div>
						}
						
					)}

					<div className="tar mr20 mb30 mt30">
					<FormattedMessage id='all_count' defaultMessage='合计'/>：{T.formatPrice(T.cutPrice(this.state.surrenderResult.feeAmount))}SGD
					</div>
				</div>
			}
		    

			<div className="whiteSpace"></div>
			<div className="footer clearfix">
				<Flex>
					{/* <Flex.Item className="tac pt30 pb30">
						<Checkbox checked={this.state.chooseAll} className="mr20" onChange={this.chooseAllInsure} sid="0" />
						<FormattedMessage id='all_choose' defaultMessage='全选'/>
					</Flex.Item> */}
					<Flex.Item className="tac pt30 pb30 fcw f28 diy_background" onClick={this.submitTry}>{btnText}</Flex.Item>
				</Flex>
			</div>
	  	</div>)
	}
}

export default connect(state => {
    return state.surrenderInfo;
  })(App)